package com.sl.core.engine.meta.valuemeta;

import cn.hutool.core.collection.CollUtil;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang.StringUtils;
import org.apache.hop.core.row.IValueMeta;
import org.apache.hop.core.row.value.ValueMetaBase;
import org.apache.hop.core.row.value.ValueMetaPlugin;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


@ValueMetaPlugin(id = ValueMetaArray.TYPE, name = "Array", description = "ARRAY")
public class ValueMetaArray extends ValueMetaBase implements ObjArrayMetaInterface {
    private List<IValueMeta> fields;


    public static final String TYPE = "12";
    /**
     * 数组里存放的对象类型
     */
    @Getter
    @Setter
    private IValueMeta fieldType;

    public ValueMetaArray() {
        this(null);
    }

    public ValueMetaArray(String name) {
        super(name, Integer.parseInt(TYPE), -1, -1);
    }

    @Override
    public Object getNativeDataType(Object object) {
        return object;
    }

    @Override
    public Class<?> getNativeDataTypeClass() {
        return Collection.class;
    }

    @Override
    public List<IValueMeta> getFields() {
        return this.fields;
    }

    @Override
    public void setFields(List<IValueMeta> fields) {

        synchronized (this) {
            this.fields = new ArrayList<>();
        }
        if (CollUtil.isEmpty(fields)) {

            this.fields.clear();
            return;
        }
        this.fields.addAll(fields);
    }

    @Override
    public void addField(IValueMeta childMete) {
        if (fields == null) {
            synchronized (this) {
                if (fields == null) {
                    fields = new ArrayList<>();
                }
            }
        }
        fields.add(childMete);
    }

    @Override
    public void addFields(List<IValueMeta> childMete) {
        if (fields == null) {
            synchronized (this) {
                if (fields == null) {
                    fields = new ArrayList<>();
                }
            }
        }
        fields.addAll(childMete);
    }

    @Override
    public IValueMeta getField(String fieldName) {
        if (CollUtil.isEmpty(fields)) {
            return null;
        }
        for (IValueMeta field : fields) {
            if (StringUtils.equals(field.getName(), fieldName)) {
                return field;
            }
        }
        return null;
    }


}
